You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 0 -> 8 Explanation: 342 + 465 = 807.
# Definition for singly-linked list.# class ListNode:# def __init__(self, x):# self.val = x# self.next = NoneclassSolution: defaddTwoNumbers(self, l1: ListNode, l2: ListNode) ->ListNode: l3=ListNode(0) curr=l3carry=0whilel1orl2: curr.next=ListNode(carry) curr=curr.nextcurr.val+=l1.valifl1else0curr.val+=l2.valifl2else0carry=curr.val//10curr.val%=10l1=l1.nextifl1elseNonel2=l2.nextifl2elseNoneifcarry: curr.next=ListNode(carry) returnl3.next
# Definition for singly-linked list.# class ListNode# attr_accessor :val, :next# def initialize(val = 0, _next = nil)# @val = val# @next = _next# end# end# @param {ListNode} l1# @param {ListNode} l2# @return {ListNode}defadd_two_numbers(l1,l2)l3=ListNode.newcurr=l3carry=0whilel1orl2curr.next=ListNode.new(carry)curr=curr.nextcurr.val += l1.valifl1curr.val += l2.valifl2carry=curr.val / 10curr.val %= 10l1=l1.nextifl1l2=l2.nextifl2endcurr.next=ListNode.new(carry)ifcarry == 1returnl3.nextend